package com.howells.time.module.discovery.view;

import android.app.Service;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.Toast;

import com.howells.time.R;
import com.howells.time.base.utils.ToastShow;
import com.howells.time.module.UIHelper;
import com.howells.time.module.discovery.model.DiscoveryMode;
import com.howells.time.module.discovery.presenter.DiscoveryPresenter;
import com.howells.time.module.discovery.presenter.DiscoveryPresenterImp;
import com.howells.time.module.discovery.presenter.ShakeListener;
import com.orhanobut.logger.Logger;
import com.zhy.base.adapter.recyclerview.OnItemClickListener;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;

import jp.wasabeef.recyclerview.animators.FlipInBottomXAnimator;


/**
 * Created by Administrator on 2016.5.8.
 */
public class DiscoveryFragment extends Fragment implements DiscoveryView,OnRefreshListener{

    private DiscoveryPresenter mDiscoveryPrenter;
    private RecyclerView mDiscoverView;
    private List<DiscoveryMode> list;
    private List<DiscoveryMode> listcache;
    private SwipeRefreshLayout swipeRefreshLayout;
    private DiscoveryAdapter adapter;
    private View view;

    private ShakeListener mShakeListener;
    private SensorManager mSensorManager;
    private Vibrator vibrator;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_discovery, container, false);

        init();
 //       timer.schedule(task,1000,1000);

        mDiscoveryPrenter=new DiscoveryPresenterImp(this);
        mShakeListener = new ShakeListener(this);
        vibrator=(Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        //获取传感器管理服务
        mSensorManager = (SensorManager) getContext().getSystemService(Service.SENSOR_SERVICE);
        //加速度传感器
        mSensorManager.registerListener(mShakeListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                //还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等，
                //根据不同应用，需要的反应速率不同，具体根据实际情况设定
                SensorManager.SENSOR_DELAY_NORMAL);
        mSensorManager.unregisterListener(mShakeListener);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void init() {
        list=new LinkedList<>();
        for(int i=0;i<6;i++) {
            DiscoveryMode discoveryMode = new DiscoveryMode();
            discoveryMode.setImageView("http://img.my.csdn.net/uploads/201407/26/1406383166_2224.jpg",null);
            list.add(discoveryMode);
        }

        listcache=new LinkedList<>();

        mDiscoverView= (RecyclerView) view.findViewById(R.id.discovery_recycler);
        mDiscoverView.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
  //      mDiscoverView.setItemAnimator(new SlideInLeftAnimator());
        adapter=new DiscoveryAdapter(view.getContext(),R.layout.item_discovery,list);
        mDiscoverView.setAdapter(adapter);

        mDiscoverView.getItemAnimator().setAddDuration(500);
        mDiscoverView.getItemAnimator().setRemoveDuration(500);
        mDiscoverView.getItemAnimator().setMoveDuration(500);
        mDiscoverView.getItemAnimator().setChangeDuration(500);

        mDiscoverView.setItemAnimator(new FlipInBottomXAnimator(new OvershootInterpolator(1f)));

        swipeRefreshLayout= (SwipeRefreshLayout) view.findViewById(R.id.swiperefreshdiscovery);
        swipeRefreshLayout.setOnRefreshListener(this);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, View view, Object o, int position) {
                Toast.makeText(DiscoveryFragment.this.getContext(), "[position:" + view.getTag()+"--"+((DiscoveryMode)o).getUrl(), Toast.LENGTH_SHORT).show();
                //跳转到新的activity
                UIHelper.jumpVideo(getActivity());
            }

            @Override
            public boolean onItemLongClick(ViewGroup parent, View view, Object o, int position) {
                return false;
            }
        });

    }

    @Override
    public void resultMsg(String msg) {
        ToastShow.ToastShort(getContext(),msg);
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
                ToastShow.ToastShort(getContext(),"刷新成功");
            }
        },1000);
    }

    @Override
    public void shakeaction() {
    //    mDiscoveryPrenter.loadDiscovery(null);
        Map<String,String> info=new HashMap();
        info.put("maxTime","0");
        info.put("rowNum","10");

        mDiscoveryPrenter.loadDiscovery(info);
    }

    @Override
    public void loadFinish(List info) {


        long[] pattern={100,400,100,400};
        vibrator.vibrate(pattern,-1);
        add(0);
        ToastShow.ToastShort(getContext(),"刷新成功");
    }

    public void remove(int position){
        listcache.add(0,list.get(position));
        if(listcache.size()>=8){
            listcache.remove(listcache.size()-1);
        }
        list.remove(position);
        adapter.notifyItemRemoved(position);
        Log.d("DiscoveryFragment", "list.size():" + list.size());
        Log.d("DiscoveryFragment", "listcache.size():" + listcache.size());
    }

    public void add(int positon){

        DiscoveryMode discoveryMode = new DiscoveryMode();
    //    discoveryMode.setImageView(null,null);

        if(list.size()<8){
            list.add(positon, discoveryMode);
            adapter.notifyItemInserted(positon);
        }else {
            remove(list.size()-1);
            list.add(positon,listcache.get(listcache.size()-1));
            adapter.notifyItemInserted(positon);
        }
    }


    //定时刷新
    Timer timer;
    Handler handler;
    private boolean isstop=true;
    public void timerstart() {
        Logger.d("start22222222222222");
        Map<String,String> info=new HashMap();
        info.put("maxTime","1480566537013");
        info.put("rowNum","10");

        mDiscoveryPrenter.loadDiscovery(info);
/*
        handler = new Handler() {

            public void handleMessage(Message msg) {
                if (msg.what == 1) {
                    add(0);
              //      lastTofirst();

             //       定时的网络请求


                    Map info=new HashMap();
                    mDiscoveryPrenter.loadDiscovery(info);

                }
                super.handleMessage(msg);
            };
        };

        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                // 需要做的事:发送消息
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };

        if(isstop) {
            timer = new Timer();
            timer.schedule(task, 1000, 500*2);
            isstop=false;
        }*/
    }
    public void timerstop() {

        if (!isstop) {
            timer.cancel();
            timer = null;
            isstop = true;
        }
    }
}
